/**
 * Created with IntelliJ IDEA.
 * User: mkadush
 * Date: 12.09.13
 * Time: 8:34
 * To change this template use File | Settings | File Templates.
 */

var onCompleteEdit = function (treeEditor, newValue, oldValue) {
    var editNode = treeEditor.editNode;
    var editNodeId = editNode.id;
    Ext.Ajax.request({
        url: '../organization/jsonUpdateNodeName',
        params: {
            id: editNodeId,
            newName: newValue
        },
        success: function (response, opts) {
            var responseJson = Ext.decode(response.responseText);
            if (responseJson.success !== true) {
                editNode.setText(oldValue);
                Ext.MessageBox.alert(responseJson.msg);
             } else {
                var treePanel = Ext.getCmp('treepanel');
                var prefixId = editNode.attributes.id.substring(0, 4);
                var currentForm = getCurrentForm(prefixId);
                var name = currentForm.getForm().findField('name');
                name.setValue(editNode.attributes.text);
            }
        },
        failure: function (response, opts) {
            editNode.setText(oldValue);

            Ext.Msg.alert('failure!');
        }
    });
};


var onEdit = function () {
    var treePanel = Ext.getCmp('treepanel');
    var selectedNode = treePanel.getSelectionModel().getSelectedNode();

    if (!this.treeEditor) {
        this.treeEditor = new Ext.tree.TreeEditor(treePanel, {}, {
            cancelOnEsc: true,
            completeOnEnter: true,
            selectOnFocus: true,
            allowBlank: false,
            listeners: {
                complete: onCompleteEdit
            }
        });
    }

    this.treeEditor.editNode = selectedNode;
    this.treeEditor.startEdit(selectedNode.ui.textNode);


};


var onCompleteAdd = function (btn, e) {
    var tree = Ext.getCmp('treepanel');
    var selectedNode = tree.getSelectionModel().getSelectedNode();
    var parentId = selectedNode.attributes.id.substring(0, 4);
    var prefixId = parentId == 'org_' ? 'dep_' : parentId == 'dep_' ? 'pro_' : 'hum_';

    var currentForm = getCurrentForm(prefixId);

    currentForm.getForm().submit({
        url: '../Organization/saveDataFromForm',
        params: {   parentId: selectedNode.attributes.id  },
        success: function (form, action) {
            var responseJson = Ext.decode(action.response.responseText);
            selectedNode.expand(null, null, function () {
                var newNodeCfg = {
                    text: responseJson.name,
                    id: responseJson.id,
                    leaf: (selectedNode.id.substring(0, 3) == 'pro'),
                    iconCls: responseJson.iconCls,
                    children: []
                };
                var newNode = selectedNode.insertBefore(newNodeCfg, selectedNode.firstChild);

            }, this);
           currentForm.getForm().reset();
            Ext.MessageBox.alert(action.result.msg)
        },
        failure: function (form, action) {
            Ext.MessageBox.alert(action.result.msg);

//            var centerRegion = Ext.getCmp('centerRegion');
//            for (var i = 0; i < centerRegion.items.getCount(); i++) {
//                centerRegion.items.itemAt(i).hide()
//            }
        }


    });

};

var onAdd = function () {
    var treePanel = Ext.getCmp('treepanel');
    var selectedNode = treePanel.getSelectionModel().getSelectedNode();

    var parentId = selectedNode.attributes.id.substring(0, 4);
    var prefixId = parentId == 'org_' ? 'dep_' : parentId == 'dep_' ? 'pro_' : 'hum_';

    var centerRegion = Ext.getCmp('centerRegion');
    for (var i = 0; i < centerRegion.items.getCount(); i++) {
        centerRegion.items.itemAt(i).hide()
    }

    var currentForm = getCurrentForm(prefixId);
    var saveButtonPanel = Ext.getCmp('saveButtonPanel');

    currentForm.show();
    currentForm.getForm().reset();
    saveButtonPanel.show();

    var saveButton = Ext.getCmp('saveButton');
    saveButton.removeListener('click', onButtonSaveClick);
    saveButton.addListener('click', onCompleteAdd);
    saveButton.setText('Добавить');

};

var onConfirmDelete = function (btn) {
    if (btn !== 'yes') {
        return
    }
    var treePanel = Ext.getCmp('treepanel');
    var selNode = treePanel.getSelectionModel().getSelectedNode();

    Ext.Ajax.request({
        url: '../organization/jsonDeleteNode',
        params: {
            id: selNode.id
        },
        success: function (response, opts) {
            var responseJson = Ext.decode(response.responseText);
            if (responseJson.success === true) {
                selNode.remove();

            } else {
                Ext.MessageBox("An error occurred with server")
            }
            var centerRegion = Ext.getCmp('centerRegion');
            for (var i = 0; i < centerRegion.items.getCount(); i++) {
                centerRegion.items.itemAt(i).hide()
            }
        }
    });
};


var onDelete = function () {
    var treePanel = Ext.getCmp('treepanel');
    var selNode = treePanel.getSelectionModel().getSelectedNode();

    if (!selNode) {
        return;
    }
    Ext.MessageBox.confirm('Вы уверены?', 'Подтвертите удаление: ' + selNode.attributes.text, onConfirmDelete);
};

